package leo.gptBot.thread;

import leo.gptBot.constant.PostTypeEnum;
import leo.gptBot.dispenser.MessageDispenser;
import leo.gptBot.dto.request.Message;
import leo.gptBot.utils.ApplicationContextProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Leo
 * @date ：Created in 2024/7/22 15:05
 * @description：
 */
@Slf4j
public class ProcessMessageTask implements Runnable{

    private final WebSocketSession session;
    private final Message bean;
    private ProcessMessageTask(WebSocketSession session,Message bean){
        this.session = session;
        this.bean = bean;
    }

    private final static ThreadPoolExecutor threadPool;

    private static final MessageDispenser messageDispenser;
//    private static final NoticeDispenser noticeDispenser;
    static {
        messageDispenser = ApplicationContextProvider.getBean(MessageDispenser.class);
//        noticeDispenser = ApplicationContextProvider.getBean(NoticeDispenser.class);
        threadPool = new ThreadPoolExecutor(16, 31, 10L * 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));
    }

    @Override
    public void run() {
        try {
            if(PostTypeEnum.message.toString().equals(bean.getPostType())){
                // 普通消息
                final String msg = bean.getRawMessage();
                log.info("[{}]收到来自用户[{}]的消息:{}",bean.getMessageType(),bean.getUserId(),msg);
                if(msg != null){
                    messageDispenser.onEvent(session,bean,msg);
                }
            }else if(PostTypeEnum.notice.toString().equals(bean.getPostType())){
                //TODO
                log.info("暂不支持通知类型");
            } else {
                log.info("未知PostType: {}",bean.getPostType());
            }
        }catch (Exception e){
            log.error("处理消息时异常",e);
        }

    }

    public static void execute(final WebSocketSession session,final Message bean){
        threadPool.execute(new ProcessMessageTask(session,bean));
    }
}
